05b - Python basics

05b - Python basics

What’s Python?

Python is an Open Source project of an interpreted high-level programming language. It also provides a wide variety of libraries, which enable quick and easy implementation of both simple and advanced programming tasks. Python serves great as a tool for everyday computer scripting and automation of tasks. The interpreter is available for many platforms, including Windows, Linux, and macOS. Python has also become one of the most popular tools for data analisys in science, next to R and MATLAB.

Creating a new project in PyCharm

If after opening PyCharm you see an existing project open, close it using menu FileClose Project:

1a_close_project

A welcome window should appear, click Create New Project:

1b_new_project

In the following window, specify the project’s name and location (1). Warning Avoid using non-ASCII characters (e.g. accented and diacritical characters), and whitespaces in name and location of the project. Spaces can be substitutet with an underscore (_).

Next, unfold Project Interpreter: tab (2) and select Existing interpreter (3). Confirm with Create button (4).

2_new_project_settings

The project is empty by default. To add a new file, right-click on the project’s name (1), and from the context menu choose New (2) → Python File (3) :

3_new_python_file

A pop-up window will appear asking for the name of a newly created file. Enter the filename and confirm with ENTER:

4_file_name

🔨 🔥 Assignment 🔥 🔨

Create a new project called hello_python according to above tutorial. Add a single file to the project, named my_first_script.py.


Python console in PyCharm

Python is an interpreted, scripting language. Because of that, commands can be run interactively, using the console interpreter. PyCharm has a built-in windows containing a Python console. To run it, click Python Console (1) in the bottom-left corner. After a short while, a Python interpreter will be launched, and command prompt will appear (2).

5_python_console

🔨 🔥 Assignment 🔥 🔨

Launch Python console in PyCharm programming environment.


Python basics

Basic mathematical operations

In Python, you can use basic mathematical operators: +, -, * i /. The language keeps the standard order of operations. To change the order, use round parentheses (()):

>>> 3 + 5
8
>>>  9 - 8 * 100
-791
>>> (9 - 8) * 100
100

Division (/) always returns a real number, even with integers as operands:

>>> 100 / 6
16.666666666666668

To perform an integer division, a // operator is available. To get the remainder, a % modulo operator can be used:

>>> 100 // 6
16
>>> 100 % 6
4

Exponentiation can be done using operator **:

>>> 2 ** 16
65536

🔨 🔥 Assignment 🔥 🔨

  1. In the previously launched Python console check the results of using above operators. Verify order of computation.

Variables

As in most programming languages, a value can be assigned to a variable in Python. There is no need to declare the variable beforehand or specify its type - it will be determined by the interpreter based on the value. Assignment is done using = operator, which assigns value on the right to a variable on the left:

>>> base = 20
>>> height = 3
>>> base * height / 2
30.0

Computed results can also be saved to a variable:

>>> net_price = 100
>>> tax = 0.23
>>> gross = net_price + net_price * tax
>>> gross
123

Apart from numbers such as int or float variables can store more advanced objects, such as strings. In Python strings are declared using either single '...' or double "..." quotation marks. Either style can be used, but it’s a good practice to be consistent across a program. If you want to embed a quotation mark itself in a string, it has to be escaped using a backslash (\):

>>> s1 = "Alice has a cat"
>>> s2 = 'The other Alice has a cat too`
>>> s2 = "Alice said: \"This is not my cat\""
>>> s3 = 'Don\'t say that Ala!'

Strings can be joined using addition (+) operator:

>>> prefix = "http://www."
>>> domain = "google.com"
>>> prefix + domain
'http://www.google.com'

🔨 🔥 Assignment 🔥 🔨

  1. Using the console, enter two catheti (sides of a rectangular triangle) as variables a and b. Calculate the area of that triangle and assign to a variable called A.
  2. Calculate the hypotenuse (the side opposite the right angle) and save as variable c. Hint: Remember that calculating a square root is the same as raising a number to the power of 0.5.
  3. Based on above operations, calculate the triangle’s circumference.

Displaying data

As you can see, when using the interactive mode, Python always displays the result of the last operation. If you want to specify a message to be displayed manually (or later, when using scripts), use print() function. You can specify multiple arguments, by default they will be displayed in a single line, separated with spaces:

>>> print('Hello!')
Hello!
>>> name = 'Joaquin'
>>> age = 21
>>> height = 1.80
>>> print('This is', name, ', he is', age, 'years old and measures', height, 'm')
This is Joaquin , he is 21 years old and measures 1.8 m

Lists

In Python, the most frequently used container to store a series of variables is a list. A list can be declared using square brackets, with elements separated with commas:

>>> primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

Internally, Python list resembles a C++ vector. Elements can be accessed using a [] operator, indexes start at 0. Similiarly to MATLAB, single elements can be accessed, as well as ranges in the format start:stop:step (each of the range parameters is optional):

>>> primes[0]
2
>>> primes[-1]  # last element
37
>>> primes[1:4] # right-open interval
[3, 5, 7]
>>> primes[3:]  # elements from 4th (index 3) to the end
[7, 11, 13, 17, 19, 23, 29, 31, 37]
>>> primes[::2] # every other element
[2, 5, 11, 17, 23, 31]

Lists can be concatenated using addition operator:

>>> primes + [41, 43, 47, 53, 59, 61, 67]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]

Accessed elements can of course be modified:

>>> my_list = [1, 2, 3]
>>> my_list[0] = 3
>>> my_list
[3, 2, 3]

New elements can be added to the end of the list using append() method:

>>> my_list.append(2)
>>> my_list
[3, 2, 3, 2]

Contrary to C++ containers, a Python list can contain multiple types of elements, including other lists:

>>> mixed_type_list = [1, "string", 0.43, [1, 2, 3, 4], ['a', 1, 'g']]

Number of elements in a container (including a string) can be accessed using a len() function:

>>> len("Hello")
5
>>> len(primes)
12
>>> len(my_list)
4
>>> len(mixed_type_list)
5
>>> len(mixed_type_list[4])
3

🔨 🔥 Assignment 🔥 🔨

  1. Using interactive console, create (manually) a list containing numbers from 0 to 12 (inclusive) and save it to a variable source
  2. Create another list, containing two lists: the first will contain even numbers from list source, the second one will contain odd numbers. Use [] operator with proper ranges.
  3. Create a third list, containing lengths of lists created in task 2.

Python in system console

Python interpreter is just a console program, it can be run directly from the system command line. In Microsoft Windows, launch the terminal by pressing Windows + R. A Run window will appear. Type cmd program name (1) and confirm by pressing ENTER (2).

6_windows_cmd

A terminal window should appear. Depending on the way Python was installed, it can be run by executing either:

python3

or

python

A Python interpreter will be launched and command prompt will appear: >>> _.


🔨 🔥 Assignment 🔥 🔨

Using system console, create a short list and print its contents.


Executable scripts

While interactive interpreter is useful to perform very short operations or test some features, more complex programs are created as executable scripts - text files containing all the commands in concecutive lines. Python scripts have .py extension. At the beginning of the classes, we created our first script: my_first_script.py.


🔨 🔥 Assignment 🔥 🔨

In my_first_script.py paste the following code:

print("Hello Python!")

name = 'XYZ'
age = 20

print("My name is", name, "and I'm ", age, "years old")

To execute the script for the first time, right click on the editor tab of the script and select Run ‘script name, or press Ctrl + Shift + F10:

7_first_run

In PyCharm’s bottom dock a Run tab will appear (1), containing the output of our script (2):

8_run_console

Each following execution of the script can be done by simply pressing Play (1) in top-right corner or by pressing Shift + F10. If you have more than one script in the project, current Run configuration can be selected from a drop-down list (2):

9_rerun

🔨 🔥 Assignment 🔥 🔨

  1. Execute my_first_script.py.
  2. Modify the script with your personal data and run it again.

Comments

Comments can be used to leave information about specific parts of code for programmers (including yourself!). Beginning with #, all text after the comment symbol is ignored by the interpreter until the end of line.

# full-line comment
x = 5  # assignment of number 5 to variable x

# comments can be used to deactivate parts of code:
# print('Bye Python!')

for loop

In Python, for loop iterates over elements of any iterable container, such as a list or a string. For example:

students = ['Mark', 'Alice', 'Frank', 'Catherine']
for s in students:
    print(s, len(s))
print()  # prints an empty line

for character in students[1]:
    print(character)
    print("ASCII:", ord(character))  # ord() returns a character's ASCII code as an integer

Mark 4 Alice 5
Frank 5
Catherine 9

A ASCII: 65
l
ASCII: 108
i
ASCII: 105
c
ASCII: 99
e
ASCII: 101

Take note how for loop body is defined - there are no brackets (as in C/C++) or “end” directive (as in MATLAB). Instead, indentation is used to specify which parts of code should be included in a loop. Indentation can be increased (shifted to right) using TAB or decreased (shifted left) using Shift + Tab. A command which is not indented (see print() # prints an empty line) is not a part of the loop. This way is used not only for loops, but also conditional statements and functions in Python. It is also possible to nest loops using multiple indentation levels:

students = ['Mark', 'Alice', 'Frank', 'Catherine']
for s in students:
    print(s)
    for character in s:
        print(character)
        print("ASCII:", ord(character))

    print()

range() function

If a series of operations has to be done for several consevutive integers, a range() function can be used to generate an arithmetic series, in conjuction with for loop:

for n in range(10):   # generates a range from 0 to 9 (right-open interval)
    print(n, end=" ") # end=" " changes the default newline ending character to a space

0 1 2 3 4 5 6 7 8 9

for n in range(2, 11): # a range from 2 to 10
    print(n, end=" ")

2 3 4 5 6 7 8 9 10

for n in range(-10, 100, 10): # generuje zakres od -10 do 90, z krokiem 10
    print(n, end=" ")

-10 0 10 20 30 40 50 60 70 80 90

range() can be used to iterate over a list using indexes, not the values of themselves:

animals = ['Dog', 'Cat', 'Monkey', 'Tiger', 'Parrot']
for animal_index in range(len(animals)):
    animals[animal_index] = str(animal_index) + ". " + animals[animal_index]
    # animal_index is an integer, to convert it to a string, an str() function is used

print(animals)

[‘0. Dog’, ‘1. Cat’, ‘2. Monkey’, ‘3. Tiger’, ‘4. Parrot’]


🔨 🔥 Assignment 🔥 🔨

Write a script in which you:

  1. Declar a list of several numbers.
  2. In a loop, print square of each of the numbers in the format: Square of X is Y
  3. Add two variables start and end which will specify a range, for which you will display cubes of the numbers. For example, if your input list contains numbers 1, 3, 5, 6, 11, start=1, end=3, the script should display:

Cube of 3 is 27 Cube of 5 is 125 Cube of 6 is 216


Conditional statement: if elif else

Conditional statements allow you to execute parts of the code only if some condition was met. In Python, a basic if usage is as follows:

if x < 0:
    print('Negative value')
elif x == 0:
    print('Zero')
elif x == 1:
    print('One')
else:
    print('More than one, but not zero')

As with loops, each conditional statement body is defined using indentation. elif and else clauses are optional, the most basic form of conditional statement only has to contain if keyword.

The condition can be defined using anything that returns a logical value: basic comparision operators: <, <=, >, >=, == (equal), != (not equal) or functions. More complex conditions can be built using logical operators: && (and), || (or), ! (not - negation), and grouped using round parentheses.


🔨 🔥 Assignment 🔥 🔨

Write a script:

  1. Define a list of names of your classmates (around 10).
  2. Display only those names, which are longer 5 (you can adjust the exact value). Hint Use a condition statement nested in a for loop.

Final assignment 🔥 🔨

  1. A rollercoaster can be accessed only by kids higher than 120 cm. Place the data from the below table in two lists called names and heights. Write a script which will display a welcome message only for allowed kids:
Name Height [cm]
Anna 80
John 122
Martin 140
Caroline 101
Sophie 132
Groot 120
Olaf 115

John! You are 122 cm in height, come in!
Martin! You are 140 cm in height, come in!
Sophie! You are 132 cm in height, come in!

  1. Your favorite pizza restaurant sells Pepperoni pizza in four sizes, as specified below. Declare two lists: one with sizes, the other with corresponding prices. Write a script which will find the optimal choice with respect to price per pizza area.
Diameter Price
24 cm 22,60 PLN
32 cm 32,60 PLN
42 cm 38,70 PLN
51 cm 46,30 PLN

Homework 💥 🏠

Task 1

Write a script printing a fir tree of a given height. For example, for height = 5:

    *
   ***
  *****
 *******
*********

Task 2

Write a script drawing an empty square of given side lengtht. For example, for side = 4:

****
*  *
*  *
****

Task 3

Following input text is given:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis feugiat malesuada. Cras iaculis iaculis lacus quis tempus. Quisque viverra erat sit amet odio condimentum venenatis. Aliquam accumsan porta massa. Nam fermentum gravida fringilla. Morbi ut ornare metus, id congue erat. Vestibulum in est nec dolor malesuada vulputate vitae non ligula. Sed ut elit in libero hendrerit ultricies varius suscipit diam.

Write a script, which will:

Hint: Try to do all the tasks using knowledge from this tutorial. After you succeed, search the Internet for easier alternatives. Python has many, many functions which will help you in various tasks!


Authors: Tomasz Mańkowski, Jakub Tomczyński